package com.jsyl.lwbk.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jsyl.lwbk.business.domain.Child;
import com.jsyl.lwbk.business.domain.EvaluateReport;
import com.jsyl.lwbk.business.domain.EvaluateScore;
import com.jsyl.lwbk.business.dto.*;
import com.jsyl.lwbk.business.mapper.ChildMapper;
import com.jsyl.lwbk.business.mapper.EvaluateReportMapper;
import com.jsyl.lwbk.business.mapper.EvaluateScoreMapper;
import com.jsyl.lwbk.business.service.IEvaluateReportService;
import com.jsyl.lwbk.business.vo.ChildReportVO;
import com.jsyl.lwbk.common.exception.BusinessException;
import com.jsyl.lwbk.common.utils.DateUtils;
import com.jsyl.lwbk.common.utils.StringUtils;
import com.jsyl.lwbk.system.mapper.SysDictDataMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class EvaluateReportServiceImpl implements IEvaluateReportService {

    @Autowired
    EvaluateReportMapper evaluateReportMapper;
    @Autowired
    EvaluateScoreMapper evaluateScoreMapper;
    @Autowired
    ChildMapper childMapper;
    @Autowired
    SysDictDataMapper sysDictDataMapper;

    @Override
    public List<ChildReportVO> getChildReport(ChildReportDTO childReportDTO) {
         List<ChildReportVO> list = evaluateReportMapper.findByChildId(childReportDTO.getChildId(), childReportDTO.getEvaluateNumber(), childReportDTO.getBeginTime(), childReportDTO.getEndTime());

        String evaluateNumber = "";//只有最后一条能修改
        EvaluateReport evaluateReport = evaluateReportMapper.findLastEvaluateReport(childReportDTO.getChildId());
        if (evaluateReport != null && evaluateReport.getStatus() == 1 && DateUtils.dayCompareDay(evaluateReport.getCreateTime(), new Date()) <= 30) {
            evaluateNumber = evaluateReport.getEvaluateNumber();
        }
         if (StringUtils.isNotEmpty(evaluateNumber)) {
            for (int i = 0; i < list.size(); i++) {
                ChildReportVO childReportVO = list.get(i);
                if (childReportVO.getEvaluateNumber().equals(evaluateNumber)) {
                    list.get(i).setEdit(1);
                    break;
                }
            }
        }
        return list;
    }



    /**
     * 通过 evaluateNumber查询对应记录
     *
     * @param evaluateNumber
     * @return
     */
    @Override
    public EvaluateReport findByEvaluateNumber(String evaluateNumber) {
        return evaluateReportMapper.findByEvaluateNumber(evaluateNumber);
    }

    /**
     * 获取表单合成
     *
     * @param evaluateNumber
     * @return
     */
    @Override
    public ReportTableDTO getReportTableDTO(String evaluateNumber) {
        EvaluateReport evaluateReport = evaluateReportMapper.findByEvaluateNumber(evaluateNumber);
        if (evaluateReport == null) {
            throw new BusinessException("该测评已失效");
        }
        Child child = childMapper.selectById(evaluateReport.getChildId());

        ReportTableDTO reportTableDTO = new ReportTableDTO();
        reportTableDTO.setChileName(child.getName());
        reportTableDTO.setChildSex(child.getSex().equals((byte)1) ? "男" : "女");
        reportTableDTO.setChildBirthday(child.getBirthYear() + "-" + child.getBirthMonth() + "-" + child.getBirthDay());
        reportTableDTO.setTeacherName(evaluateReport.getCreateBy());
        reportTableDTO.setEvaluateTime(DateUtils.dateTime(evaluateReport.getCreateTime()));
        reportTableDTO.setEvaluateVersion(evaluateReport.getEvaluateVersion() + "");
        if (evaluateReport.getStatus() == 0) {
            List<ReportScoreDTO> evaluateModuleScoreDTOList = evaluateScoreMapper.findEvaluateModuleScoreByEvaluateNumber(evaluateNumber);
            List<ReportScoreDTO> projectModuleScoreDTOList = evaluateScoreMapper.findProjectModuleScoreByEvaluateNumber(evaluateNumber);
            reportTableDTO.setReportTableProjectDTO(changeReportTableProjectDTO(projectModuleScoreDTOList));
            reportTableDTO.setReportTableEvaluateDTO(changeReportTableEvaluateDTO(evaluateModuleScoreDTOList));
        } else {
            reportTableDTO.setReportTableProjectDTO(new ReportTableProjectDTO());
            reportTableDTO.setReportTableEvaluateDTO(new ReportTableEvaluateDTO());
        }
        return reportTableDTO;
    }

    public ReportTableEvaluateDTO changeReportTableEvaluateDTO(List<ReportScoreDTO> evaluateModuleScoreDTOList) {
        JSONObject jsonObject = new JSONObject();
        for (ReportScoreDTO reportScoreDTO : evaluateModuleScoreDTOList) {
            jsonObject.put("evaluateScore" + reportScoreDTO.getEvaluateModule(), reportScoreDTO.getScore());
        }
        return JSON.parseObject(jsonObject.toJSONString(), ReportTableEvaluateDTO.class);
    }

    public ReportTableProjectDTO changeReportTableProjectDTO(List<ReportScoreDTO> evaluateModuleScoreDTOList) {
        JSONObject jsonObject = new JSONObject();
        for (ReportScoreDTO reportScoreDTO : evaluateModuleScoreDTOList) {
            jsonObject.put("projectChildScore" + reportScoreDTO.getProjectModule(), reportScoreDTO.getScore());
            jsonObject.put("projectTotalScore" + reportScoreDTO.getProjectModule(), reportScoreDTO.getTotalScore());
            jsonObject.put("remark" + reportScoreDTO.getProjectModule(), reportScoreDTO.getRemark());
        }
        return JSON.parseObject(jsonObject.toJSONString(), ReportTableProjectDTO.class);
    }

    @Override
    public EvaluateReport getLatestChildReport(ChildReportDTO childReportDTO) {
        EvaluateReport evaluateReport  = evaluateReportMapper.getLatestChildReport(childReportDTO.getChildId(), childReportDTO.getBeginTime(), childReportDTO.getEndTime());
        return evaluateReport;
    }

    @Override
    public List<ReportScoreDTO> listProjectModuleScore(String evaluateNumber) {
        List<ReportScoreDTO> projectModuleScoreDTOList = evaluateScoreMapper.findProjectModuleScoreByEvaluateNumber(evaluateNumber);
        return projectModuleScoreDTOList;
    }

    @Override
    public Map getByEvaluateNumber(String evaluateNumber) {
        EvaluateReport evaluateReport = evaluateReportMapper.findByEvaluateNumber(evaluateNumber);
        if(evaluateReport ==null){
            return null;
        }
        return getMap(evaluateReport);
    }

    @Override
    public Map getChildReportMap(Long id) {
        EvaluateReport evaluateReport = evaluateReportMapper.findByReportId(id);
        if(evaluateReport ==null){
            return null;
        }
        return getMap(evaluateReport);
    }

    private Map getMap(EvaluateReport evaluateReport) {
        // 创建渲染PDF内容
        Map<String, Object> map = new HashMap<>();

        Child child = childMapper.selectById(evaluateReport.getChildId());

        String evaluateTime = DateUtils.dateTime(evaluateReport.getUpdateTime());
        Map<String, Object> ageMap = DateUtils.toAge(Integer.parseInt(child.getBirthYear()), Integer.parseInt(child.getBirthMonth()));

        String memberTimeCode = "";
        String number = "";

        List<Child> childList = childMapper.getChildListByCenterId(child.getCenterId());
        Integer n = null;
        if (childList.size() != 0) {
            Integer i = 1;
            for (Child childView : childList) {
                if (childView.getId().equals(child.getId())) {
                    n = i;
                }
                i++;
            }
        }
        if (evaluateTime != null) {
            memberTimeCode = getCode(evaluateTime);
            if (n!=null && n >= 100) {
                number = String.valueOf(n);
            } else if (n!=null && n >= 10) {
                number = "0" + String.valueOf(n);
            } else {
                number = "00" + String.valueOf(n);
            }
            map.put("sn",  memberTimeCode + number);
        }
        // 基础信息
        map.put("childId", child.getId());
        map.put("name", child.getName());
        map.put("date", DateUtils.dateTime(evaluateReport.getUpdateTime()));
        map.put("sex", sysDictDataMapper.selectDictLabel("sys_user_sex", String.valueOf(child.getSex())));
        map.put("grade", String.valueOf(child.getGrade()));
        map.put("age", ageMap.get("age"));
        map.put("birthday", child.getBirthYear() + "-" + child.getBirthMonth() + "-" + child.getBirthDay());
        map.put("teacher", evaluateReport.getUpdateBy());

        // 表格中的数据
        Map<String, Object> projectMap = new HashMap<>();
        Map<String, Object> moduleMap = new HashMap<>();
        // 详细数据
        Map<String, Object> detailMap = new HashMap<>();

        // 情绪处理总分
        Integer emotionProcessScore = 0;
        // 情绪状态总分
        Integer emotionalStateScore = 0;
        // 自我指向总分
        Integer selfDirectedScore = 0;
        // 环境与他人总分
        Integer environmentScore = 0;

        // 按照测评编号查询档案表中的全部分数以及反馈信息
        List<EvaluateScore> evaluateScoreList = evaluateScoreMapper.findByEvaluateNumber(evaluateReport.getEvaluateNumber());
        for (EvaluateScore evaluateScore : evaluateScoreList) {
            if (evaluateScore.getEvaluateModule() == null) { // 测评类型为空代表大类
                projectMap.put(evaluateScore.getProjectModule() + "tableName", sysDictDataMapper.selectDictLabel("business_project_module", String.valueOf(evaluateScore.getProjectModule())));
                projectMap.put(evaluateScore.getProjectModule() + "tableScore", evaluateScore.getScore() + "/" + evaluateScore.getTotalScore());
                projectMap.put(evaluateScore.getProjectModule() + "tableRemark", evaluateScore.getReportRemark());
                // 构音小类合并为一个
                if (evaluateScore.getProjectModule().equals(5)) {
                    moduleMap.put("7tableName", sysDictDataMapper.selectDictLabel("business_evaluate_module", String.valueOf(7)));
                    moduleMap.put("7tableScore", evaluateScore.getScore());
                }

                detailMap.put(evaluateScore.getProjectModule() + "", evaluateScore.getScore());
            } else { // 小类型
                if (evaluateScore.getEvaluateModule().equals(10)) {
                    // 情绪状态归为情绪状态
                    emotionProcessScore = evaluateScore.getScore();
                } else if (evaluateScore.getEvaluateModule().equals(19) || evaluateScore.getEvaluateModule().equals(20) || evaluateScore.getEvaluateModule().equals(21) || evaluateScore.getEvaluateModule().equals(22)) {
                    // 情绪感知（4分）情绪理解（12分）情绪表达（16分）情绪管理（4分）归为情绪处理
                    emotionalStateScore += evaluateScore.getScore();
                } else if (evaluateScore.getEvaluateModule().equals(23) || evaluateScore.getEvaluateModule().equals(24) || evaluateScore.getEvaluateModule().equals(25)) {
                    selfDirectedScore += evaluateScore.getScore();
                } else if (evaluateScore.getEvaluateModule().equals(26) || evaluateScore.getEvaluateModule().equals(27) || evaluateScore.getEvaluateModule().equals(28)) {
                    environmentScore += evaluateScore.getScore();
                } else {
                    moduleMap.put(evaluateScore.getEvaluateModule() + "tableName", sysDictDataMapper.selectDictLabel("business_evaluate_module", String.valueOf(evaluateScore.getEvaluateModule())));
                    moduleMap.put(evaluateScore.getEvaluateModule() + "tableScore", evaluateScore.getScore());
                }
                detailMap.put(evaluateScore.getEvaluateModule() + "Name", sysDictDataMapper.selectDictLabel("business_evaluate_module", String.valueOf(evaluateScore.getEvaluateModule())));
                detailMap.put(evaluateScore.getEvaluateModule() + "Score", evaluateScore.getScore());
                detailMap.put(evaluateScore.getEvaluateModule() + "Conclusion", evaluateScore.getReportRemark());
            }
        }
        moduleMap.put("10tableName", sysDictDataMapper.selectDictLabel("business_evaluate_module", String.valueOf(10)));
        moduleMap.put("10tableScore", emotionProcessScore);
        moduleMap.put("11tableName", sysDictDataMapper.selectDictLabel("business_evaluate_module", String.valueOf(11)));
        moduleMap.put("11tableScore", emotionalStateScore);
        moduleMap.put("12tableName", sysDictDataMapper.selectDictLabel("business_evaluate_module", String.valueOf(12)));
        moduleMap.put("12tableScore", selfDirectedScore);
        moduleMap.put("13tableName", sysDictDataMapper.selectDictLabel("business_evaluate_module", String.valueOf(13)));
        moduleMap.put("13tableScore", environmentScore);
        map.put("projectMap", projectMap);
        map.put("moduleMap", moduleMap);
        map.put("detailMap", detailMap);
        return map;
    }

    //学期编码
    public String getCode(String memberTime) {

        if (memberTime.compareTo(memberTime.substring(0, 5) + "02-15") <= 0) {
            memberTime = memberTime.substring(0, 4).substring(2, 4) + "04";
        } else if (memberTime.compareTo(memberTime.substring(0, 5) + "07-31") <= 0) {
            memberTime = memberTime.substring(0, 4).substring(2, 4) + "01";
        } else if (memberTime.compareTo(memberTime.substring(0, 5) + "09-30") <= 0) {
            memberTime = memberTime.substring(0, 4).substring(2, 4) + "03";
        } else {
            memberTime = memberTime.substring(0, 4).substring(2, 4) + "02";
        }

        return memberTime;
    }

    @Override
    public List<Map> getChildListReport(String childIds) {
        List<String> childList = Arrays.asList(childIds.split(","));
        List<ChildListReportDTO> listReportDTOS = this.evaluateReportMapper.getChildListReport(childList);
        List<Map> result = new ArrayList();
        if(CollectionUtils.isNotEmpty(listReportDTOS)){
            for(String childId:childList){
                Map temp =new HashMap();
                for(ChildListReportDTO dto:listReportDTOS){
                    if(childId.equals(dto.getChildId().toString())){
                        dto.setDateDay(dto.getDateDay().substring(0,10));
                        temp.put("childId",dto.getChildId());
                        temp.put("childName",dto.getChildName());
                        if(temp.containsKey("list")){
                            List<ChildListReportDTO> list = (List<ChildListReportDTO>) temp.get("list");
                            list.add(dto);
                            temp.put("list",list);
                        }else {
                            List<ChildListReportDTO> list = new ArrayList<>();
                            list.add(dto);
                            temp.put("list",list);
                        }
                    }
                }
                if(temp !=null && temp.size()>0){
                    result.add(temp);
                }
            }
        }
        return result;
    }
}
